const mongoose = require('mongoose');
var Commend = require('../models/commend.model');  //引数据模型

//获取单个数据
exports.get = function(req,res,next){
	var id = req.params.id;
	// console.log(id);
	Commend.findById({newsId:id},function(err,result){
		// console.log(result);
		var resTree = reverseTree(data,null);
		res.json(resTree);
	})
}

//新增
exports.create = function(req,res,next){
	var commend = new Commend(req.body);  //从req.body里获取参数对象，比如{name:'lisi',gender:'男',city:'杭州'....}
	
	commend.save()
	.then(data=>{  //刷新
		res.json(data)
	})
}

//修改
exports.update = function(req,res,next){
	var id = req.params.id;  //req.param('id')
	//现在操作的都是mongoose而不是mongodb
	Commend.findByIdAndUpdate(id,{$set:req.body},{new:false})
	.then(data=>{  
		res.json({msg:'数据修改成功',status:200});  //如果你要返回数据，这个data返回的是你之前修改的那个数据内容
	})
}

//删除
exports.remove = function(req,res,next){
	var id = req.params.id;
	Commend.findByIdAndRemove(id,function(err,doc){
		if(err){
			res.json({msg:'数据删除失败',status:404})
		}else{
			res.json({msg:'数据删除成功',status:200})
		}
		
	})
}

exports.list = function(req,res,next){
	var page = (req.query.page) ? req.query.page : 1;
	var limit = (req.query.limit) ? req.query.limit : 10;
	
	var queryCondition = {};
	var name;
	if(req.query.name && req.query.name.trim().length > 0){
		name = req.query.name;
		queryCondition = {"name":new RegExp(name,'i')}
	}

	if(req.body.newsId && req.body.newsId.trim().length > 0){
		newsId = req.body.newsId;
		queryCondition = {"newsId":newsId}
	}
	
	Commend.paginate(queryCondition,{page:page,limit:limit},function(err,result){
		result.rows = result.docs;
		delete result.docs;
		res.json(result);
	});
}
